package dating.service;

import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import dating.model.User;

/**
 * Session Bean implementation class UserService
 */
@Stateless
public class UserService extends GenericService<User, Long> implements UserServiceLocal {
	
    /**
     * Default constructor. 
     */
    public UserService() {
        super(User.class);
    }
    
    public User findUserByUsername(String username){
    	User result = null;
		try {
			Query query = this.em.createQuery("from " + entityClass.getName() + " u where u.username='" + username + "'");
			 List results = query.getResultList();
		     if (results.isEmpty()) return null;
		     else if (results.size() == 1) return (User) results.get(0);
		} catch (PersistenceException e) {
			throw new ServiceException("Could not find user named "
					+ username, e);
		}


		return result;
    }

	@Override
	public boolean exists(User user) {
		User u = findUserByUsername(user.getUsername());
		if(u != null) {
			return true;
		}
		return false;
	}

	@Override
	public List<User> search(Map<String, String> params) {
		StringBuffer searchCriteria = new StringBuffer();
		searchCriteria.append("from " + entityClass.getName() + " u where 1 = 1");
		
		for (Map.Entry<String, String> entry : params.entrySet()) {

			if(entry.getKey().equals("name") && entry.getValue() != "") {
		    	searchCriteria.append(" AND u.name like :pName");
		    } else if(entry.getKey().equals("sex") && entry.getValue() != "") {
		    	searchCriteria.append(" AND u.sex = :pSex");
		    } else if(entry.getKey().equals("city") && entry.getValue() != "") {
		    	searchCriteria.append(" AND u.city = :pCity");
		    } else if(entry.getKey().equals("astral_sign") && entry.getValue() != "") {
		    	searchCriteria.append(" AND u.astralSign = :pAstralSign");
		    }
		}
		    
			Query query = em.createQuery(searchCriteria.toString());
			
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if(entry.getKey().equals("name") && entry.getValue() != "") {
				query.setParameter("pName", "%" + entry.getValue() + "%");
		    } else if(entry.getKey().equals("sex") && entry.getValue() != "") {
		    	query.setParameter("pSex", entry.getValue());
		    } else if(entry.getKey().equals("city") && entry.getValue() != "") {
		    	query.setParameter("pCity", entry.getValue());
		    } else if(entry.getKey().equals("astral_sign") && entry.getValue() != "") {
		    	query.setParameter("pAstralSign", entry.getValue());
		    }
		}		
		
		return query.getResultList();
	}
    
}
